<?php

namespace app\admin\controller;

use Alipay\EasySDK\Kernel\Factory as alipayFactory;
use app\admin\model\User;
use app\common\controller\Backend;
use EasyWeChat\Factory;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Db;
use think\Model;

/**
 * 当面收款订单管理
 *
 * @icon fa fa-circle-o
 */
class OrderFace extends Backend
{
    
    /**
     * OrderFace模型对象
     * @var \app\admin\model\OrderFace
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $order_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\OrderFace;

        $statusList = \app\admin\model\OrderFace::fetchStatus();
        $payTypeList = \app\admin\model\OrderFace::fetchPayType();
        $typeList = \app\admin\model\OrderFace::fetchType();
        $this->view->assign(['statusList' => $statusList, 'payTypeList' => $payTypeList, 'typeList' => $typeList]);
        $this->assignconfig(['statusList' => $statusList, 'payTypeList' => $payTypeList, 'typeList' => $typeList]);
        $order_id = $this->request->param('order_id');
        $this->order_id = $order_id;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看.
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $builder = $this->model->withJoin(['user', 'type', 'order'])
                ->where($where)
                ->where('order_face.is_delete', 1);
            if($this->order_id){
                $builder->where('order_face.order_id', $this->order_id);
            }
            $total = $builder
                ->order($sort, $order)
                ->count();
            $list  = $builder
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $order = \app\admin\model\Order::where(['is_delete' => 1, 'id' => $this->order_id])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['status'] == 4){
            $text = \app\admin\model\Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['continue_status'] == 2 || $order['continue_status'] == 3){
            $this->error('订单续租中');
        }
        if($order['face_status'] == 2){
            $this->error('订单当面付款中');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'add' : $name)->check($params);
                    }

                    $params['order_id'] = $order['id'];
                    $params['user_id'] = $order['user_id'];
                    $params['merchant_id'] = $order['merchant_id'];
                    $params['out_trade_no'] = \app\admin\model\OrderFace::getOutTradeNo();
                    $params['all_money'] = $params['all_money'];
                    $params['content'] = $params['content'];
                    $params['pay_type'] = $order['pay_type'];
                    $params['createtime'] = time();
                    $params['last_all_money'] = $params['all_money'];
                    $result = $this->model->save($params);
                    \app\common\model\Order::where('id', $order['id'])->update(['face_status' => 2]);
                    \app\admin\model\Order::where('id', $order['id'])->inc('face_num', 1)->update();
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign('order', $order);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $order = \app\admin\model\Order::where(['is_delete' => 1, 'id' => $this->order_id])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        $merchant_car = \app\admin\model\MerchantCar::with('cars')->where(['is_delete' => 1, 'id' => $order['merchant_car_id']])->find();
        if(!$merchant_car){
            $this->error('商家车辆不存在');
        }
        if($merchant_car['status'] == 2){
            $this->error('商家车辆已下架');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'add' : $name)->check($params);
                    }
                    if(strtotime($order['end_time']) < strtotime(strtotime($order['start_time']))){
                        $this->error('结束日期错误');
                    }
                    $last_time = strtotime("-1 month");
                    //临时下架时间
                    $merchant_car_time = \app\admin\model\MerchantCarTime::where(['is_delete' => 1])->where('end_time', '>', $last_time)->select();
                    foreach ($merchant_car_time as $ke=>$vl){
                        $is_time_cross = is_time_cross(strtotime($vl['start_time']), strtotime($vl['end_time']), strtotime($params['start_time']), strtotime($params['end_time']));
                        if($is_time_cross){
                            $this->error('租赁时间段内商家车辆会临时下架');
                        }
                    }
                    $car_price = $merchant_car['car_price'];
                    $rental_money = 0;
                    //商家车辆远期价格
                    $merchant_car_price = \app\admin\model\MerchantCarPrice::where(['is_delete' => 1, 'merchant_car_id' => $order['id']])->where('end_time', '>', $last_time)->select()->toArray();
                    $days = 0;
                    if($merchant_car_price){
                        $date_list = createDateRange($params['start_time'], $params['end_time']);
                        $new_date_list = [];
                        foreach ($date_list as $key=>$value){
                            $new_date_list[$value] = $car_price;
                            foreach ($merchant_car_price as $kk=>$vv){
                                if(strtotime($value) >= $vv['start_time'] && strtotime($value) <= $vv['end_time']){
                                    $new_date_list[$value] = $vv['price'];
                                }
                            }
                        }
                        $days = count($date_list);
                        $rental_money = array_sum($new_date_list);
                    }
                    //保险
                    $merchant_insure = \app\admin\model\MerchantCarInsure::where('id', $params['insurance_id'])->find();
                    $insurance = $merchant_insure['price']??0;
                    $all_money = bcadd($rental_money, ($merchant_car['handle_fee'] + $insurance), 2);

                    $params['id'] = $ids;
                    $params['start_time'] = strtotime($params['start_time']);
                    $params['end_time'] = strtotime($params['end_time']);
                    $params['days'] = $days;
                    $params['price'] = $car_price;
                    $params['handle_fee'] = $order['handle_fee'];
                    $params['rental_money'] = $rental_money;
                    $params['insurance'] = $insurance;
                    $params['all_money'] = $all_money;
                    $params['updatetime'] = time();
                    $result = $this->model->where('id', $ids)->update($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign('order', $order);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model
            ->field('out_trade_no,user_id,merchant_id,all_money,status,type,createtime,content,transaction_id,time_end,total_fee,pay_type,out_refund_no,refund_id,refund_time,refund_money,cancel_time,cancel_reason,liquidated_damages')
            ->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if($row){
            $user = User::where('id', $row['user_id'])->find();
            $row['user_id'] = $user['username'];
            $row['status'] = \app\admin\model\OrderFace::fetchStatus($row['status']);
            $row['pay_type'] = \app\admin\model\OrderFace::fetchPayType($row['pay_type']);
            $row['type'] = \app\admin\model\OrderFace::fetchType($row['type']);
            $row['createtime'] = date('Y-m-d H:i:s', $row['createtime']);
            $row['time_end'] = $row['time_end'] ? date('Y-m-d H:i:s', $row['time_end']) : '';
            $row['refund_time'] = $row['refund_time'] ? date('Y-m-d H:i:s', $row['refund_time']) : '';
            $row['cancel_time'] = $row['cancel_time'] ? date('Y-m-d H:i:s', $row['cancel_time']) : '';
            $row['cancel_reason'] = $row['cancel_reason'] ? \app\admin\model\OrderContinue::fetchCancelReason($row['cancel_reason']) : '';
            unset($row['merchant_id'],$row['merchant_car_id']);
        }
//        dump($row);die;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        $this->success();
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['status'] != 1 || $row['status'] != 2){
            $text = \app\admin\model\OrderFace::fetchStatus($row['status']);
            $this->error('订单'.$text);
        }
        if(!$this->request->isPost()){
            return $this->view->fetch();
        }
        Db::startTrans();
        try {
            $params = $this->request->post('row/a');
            $user_model = new User();
            if($row['status'] == 2){
                $update = ['status' => 3, 'cancel_time' => time(), 'cancel_reason' => $params['cancel_reason']];
                $out_refund_no = \app\admin\model\OrderFace::getOutRefundNo();
                $update['out_refund_no'] = $out_refund_no;
                //退款接口
                $user = $user_model->where('id', $row['user_id'])->find();
                if($row['pay_type'] == 1){//微信退款
                    $res = $this->refund($row, $user, $row['last_all_money']);
                    if($res['return_code'] == 'SUCCESS' && $res['result_code']=='SUCCESS'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['refund_id'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                        $update['last_all_money'] = 0;
                        //更新订单
                        $res = $this->model->where('id', $row['id'])->update($update);
                        \app\admin\model\Order::where('id', $row['order_id'])->dec('face_num', 1)->update();
                        if($res){
                            $platform_log = [
                                'user_id' => $row['user_id'],
                                'amount' => $row['last_all_money'],
                                'type' => 11,
                                'log_note' => '当面付订单退款',
                                'order_id' => $row['id'],
                                'order_type' => 1,
                                'createtime' => time(),
                                'total_order_id' => $row['order_id']
                            ];
                            \app\common\model\PlatformLog::insert($platform_log);
                        }
                    }else{
                        Db::rollback();
                        $this->error('取消失败');
                    }
                }else{
                    $res = $this->alipayRefund($row, $user, $row['last_all_money']);
                    if($res['code'] == '10000'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['trade_no'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = $res['refund_fee'];
                        $update['last_all_money'] = 0;
                        //更新订单
                        $res = $this->model->where('id', $row['id'])->update($update);
                        \app\admin\model\Order::where('id', $row['order_id'])->dec('face_num', 1)->update();
                        if($res){
                            $platform_log = [
                                'user_id' => $row['user_id'],
                                'amount' => $row['last_all_money'],
                                'type' => 11,
                                'log_note' => '当面付订单退款',
                                'order_id' => $row['id'],
                                'order_type' => 1,
                                'createtime' => time(),
                                'total_order_id' => $row['order_id']
                            ];
                            \app\common\model\PlatformLog::insert($platform_log);
                        }
                    }else{
                        Db::rollback();
                        $this->error('取消失败');
                    }
                }
                //更新主订单
                $count = $this->model->where(['is_delete' => 1, 'order_id' => $row['order_id']])->where('status', 'in', '1,2')->count();
                if($count == 0){
                    \app\admin\model\Order::where('id', $row['order_id'])->update(['face_status' => 4]);
                }
            }else{
                $update = ['cancel_time' => time(), 'status' => 3, 'cancel_reason' => $params['cancel_reason'], 'last_all_money' => 0];
                //更新订单
                $res = $this->model->where('id', $row['id'])->update($update);
                //更新主订单
                \app\admin\model\Order::where('id', $row['order_id'])->update(['face_status' => 4]);
                \app\admin\model\Order::where('id', $row['order_id'])->dec('face_num', 1)->update();
            }

            Db::commit();
            $this->success('取消订单成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 退款
     */
    public function return()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['status'] != 1){
            $text = \app\admin\model\OrderFace::fetchStatus($row['pay_status']);
            $this->error('订单'.$text);
        }
        if(!$this->request->isPost()){
            return $this->view->fetch();
        }
        Db::startTrans();
        try {
            $user_model = new User();
            $platform_log = [];
            $update = ['status' => 4];
            $out_refund_no = \app\admin\model\OrderChange::getOutRefundNo();
            $value['out_refund_no'] = $out_refund_no;
            //退款接口
            $user = $user_model->where('id', $row['user_id'])->find();
            if($row['pay_type'] == 1){//微信退款
                $res = $this->refund($value, $user);
                if($res['return_code'] == 'SUCCESS' && $res['result_code']=='SUCCESS'){
                    $update['out_refund_no'] = $out_refund_no;
                    $update['refund_id'] = $res['refund_id'];
                    $update['refund_time'] = time();
                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                    //更新订单
                    $res = $this->model->where('id', $value['id'])->update($update);
                    if($res){
                        $platform_log[] = [
                            'user_id' => $value['user_id'],
                            'amount' => $value['deposit'],
                            'type' => 11,
                            'log_note' => '当面付订单退款',
                            'order_id' => $value['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                            'total_order_id' => $row['order_id']
                        ];
                    }
                }
            }else{
                $res = $this->alipayRefund($value, $user, 2);
                if($res['code'] == '10000'){
                    $update['out_refund_no'] = $value['out_refund_no'];
                    $update['refund_id'] = $res['trade_no'];
                    $update['refund_time'] = time();
                    $update['refund_money'] = $res['refund_fee'];
                    //更新订单
                    $res = $this->model->where('id', $value['id'])->update($update);
                    if($res){
                        $platform_log[] = [
                            'user_id' => $value['user_id'],
                            'amount' => $value['deposit'],
                            'type' => 11,
                            'log_note' => '当面付订单退款',
                            'order_id' => $value['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                            'total_order_id' => $row['order_id']
                        ];
                    }
                }
            }

            //写入平台流水
            if($platform_log){
                \app\common\model\PlatformLog::insertAll($platform_log);
            }
            Db::commit();
            $this->success('取消订单成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    //微信退款
    public function refund($order, $user, $refund_money){
        $refundFee = $refund_money*100;
        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($order['out_trade_no'], $order['out_refund_no'], $order['all_money']*100, $refundFee, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);
        return $result;
    }

    //支付宝退款
    public function alipayRefund($order, $user, $refund_money){
        $refundFee = $refund_money*100;
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->refund($order['out_trade_no'], $refundFee);
        if(!$result){
            return false;
        }
        if($result->code != 10000){
            return false;
            $result->msg."，".$result->sub_msg.PHP_EOL;
        }
        $return_result = json_decode($result->httpBody, true);
        return $return_result['alipay_trade_refund_response'];
    }

}
